<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Services\MobileMessageService;
use App\Http\Services\OrderService;
use App\Models\Company;
use App\Models\Order;
use App\Utils\TianZhenLan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Services\OrderExport;

class OrderController extends Controller
{

    public function index(Request $request) {
        $db = Order::with('companyinfo')
            ->with('goodsinfo')
            ->with('shopinfo')
            ->with('cityinfo');
        $search     = $request->input('search');
        $company    = $search['company'];
        $city       = $search['city'];
        $status     = $search['status'];
        $mobile     = $search['mobile'];

        if ($company) {
            $db->where('company', $company);
        }

        if ($city) {
            $db->where('city', $city);
        }

        if ($status !== '') {
            $db->where('status', $status);
        }

        if ($mobile) {
            $db->where('mobile', 'like',  "%{$mobile}");
        }
        $db->orderBy('id', 'desc');
        if ($search['download']) {
            $orders = $db->get();
            return self::download($orders);
        } else {
            $orders  = $db->paginate(20);
            return self::success($orders);
        }
    }
    public static function download($orders) {
        $tableData = [
            ['ID', '编号', '状态', '卡号', '下单人', '下单手机号', '实际拍摄人', '拍摄人手机号', '品牌', '产品', '门店', '预约时间', '完成时间', '用户备注', '客服备注', '时间']
        ];
        foreach($orders as $o) {

            switch ($o->status) {
                case 0 : $status = '未预约'; break;
                case 1 : $status = '待确认'; break;
                case 2 : $status = '待拍摄'; break;
                case 3 : $status = '已完成'; break;
                case 8 : $status = '退款申请中'; break;
                case 9 : $status = '已退款'; break;
                default: $status = '未知';
            }
            array_push($tableData, [
                $o->id,
                $o->sn,
                $status,
                $o->company_card,
                $o->user_name,
                $o->mobile,
                $o->photoer_name,
                $o->photoer_mobile,
                $o->goodsinfo->company == Company::TZL ? '天真蓝' : '海马体',
                $o->goodsinfo->name,
                $o->shopinfo ? $o->shopinfo->name : '',
                $o->time,
                $o->finish_at,
                $o->note,
                $o->admin_note,
                $o->created_at
            ]);
        }
        $export = new OrderExport($tableData);
        $file = 'export/'.date('YmdHis').'.xlsx';
        Excel::store($export, $file);
        return self::success(['file' => url($file)]);
    }

    /**
     * 确认
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirm(Request $request) {
        DB::beginTransaction();
        $orderSn    = $request->input('orderSn');
        $order      = Order::where('sn', $orderSn)->first();
        $order->confirm_at = datetime();
        $order->status = Order::STATUS_CONFIRM_OK;
        $order->save();



        // 通知荣数系统
        // OrderService::notify_sip($order->id);
        try {
            OrderService::notify_sip_book_status($order->id);
            DB::commit();
            return self::success();
        } catch (\Exception $e) {
            DB::rollBack();
            return self::fail(201, "通知荣数平台失败，错误原因：" . $e->getMessage());
        }

        // 发送通知短信
        // OrderService::send_book_success_mobile_message($order->id);
    }

    public function finish(Request $request) {
        $orderSn    = $request->input('orderSn');
        $order      = Order::where('sn', $orderSn)->first();
        $order->finish_at = datetime();
        $order->status = Order::STATUS_PHOTO_OK;
        $order->save();

        // 通知荣数平台 服务完成
        OrderService::notify_sip_use_status($order->id);

        return self::success();
    }

    /**
     * 如果是对天真蓝的订单进行更改，要同步到天真蓝的系统中
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request) {
        $data = $request->input('data');
        $id = $request->input('id');
        $order = Order::find($id);
        $res = OrderService::submit_to_tzl(
            $order->sn,
            $data['shop'],
            $data['time'],
            $data['user_name'],
            $order->mobile,
            $data['photoer_name'],
            $data['photoer_mobile'],
            $order->note,
            $data['kefu_note']
        );
        if ($res['code'] == 200) {
            return self::success();
        } else {
            return self::fail($res['code'], $res['msg']);
        }
    }

    /**
     * 取消订单 指将用户的预定信息取消 客户自己去荣数平台发起退款操作
     */
    public function cancel(Request $request) {
        $id = $request->input('id');
        $order = Order::find($id);

        if ($order->company == Company::TZL) {
            $order->status = Order::STATUS_CANCEL_LOCK;
            $order->save();
            $res = TianZhenLan::cancel_order($id);
            if ($res === false) {
                return self::fail(201, TianZhenLan::$error);
            }
            return self::success(null, 200, '取消已申请');
        } elseif ($order->company == Company::HMT) {

            Order::reset($id);
            return self::success(null, 200, '已重置该订单');
        }
    }
}
